var http = require('http')
var fs = require('fs')
var app = http.createServer()
let users = []
let socketM = {}
app.on('request', function (request, response) {
  // console.log('收到客户端请求，请求路径是：' + request.url)
  var url = request.url
  if (url === '/') {
    fs.readFile('./view/index.html', function (err, data) {
      if (err) {
        return response.end('404 Not Found')
      }
      response.end(data)
    })
  }
  else if (url.indexOf('/public/') === 0) {
    fs.readFile('.' + url, function (err, data) {
      if (err) {
        return response.end('404 Not Found')
      }
      response.end(data)
    })
  }
})
app.listen(3000, function () {
  console.log('服务器启动成功了，可以通过http://localhost:3000/ 进行访问')
})
const io = require('socket.io')(app)
io.on('connection', socket => {
  socket.on('login', data => {
    let user = users.find(item => item.username === data.username)
    if (user) {
      socket.emit('loginError', { msg: '登入失败,用户名已有' })
    }
    else {
      users.push(data)
      socket.emit('loginSuccess', data)
      io.emit('addUser', data)
      io.emit('userList', users)
      socket.username = data.username
      socket.img = data.img
    }
  })
  socket.on('disconnect', () => {
    let ids = users.findIndex(item => item.username === socket.username)
    users.splice(ids, 1)
    console.log(users)
    io.emit('delUser', { username: socket.username, img: socket.img })
    io.emit('userList', users)
  })
  socket.on('sendMessage', data => {
    io.emit('receiveMessage', data)
  })
})